package com.remainder.resource.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.remainder.common.core.domain.R;
import com.remainder.common.core.exception.BusinessException;
import com.remainder.common.core.utils.DateUtils;
import com.remainder.resource.api.domain.ExportLogDto;
import com.remainder.resource.mapper.IExportLogMapper;
import com.remainder.resource.service.IExportLogService;
import com.remainder.system.api.RemoteConfigService;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 导出记录Service业务层处理
 *
 * @author yhf
 * @date 2023-06-13
 */
@Slf4j
@Service
public class ExportLogServiceImpl implements IExportLogService {

    @Resource
    private IExportLogMapper iExportLogMapper;

    @Resource
    private RemoteConfigService remoteConfigService;

    /**
     * 查询导出记录
     *
     * @param id
     *            导出记录主键
     * @return 导出记录
     */
    @Override
    public ExportLogDto selectExportLogById(Long id) {
        return iExportLogMapper.selectExportLogById(id);
    }

    /**
     * 查询导出记录列表
     *
     * @param exportLog
     *            导出记录
     * @return 导出记录
     */
    @Override
    public List<ExportLogDto> selectExportLogList(ExportLogDto exportLog) {
        return convert(iExportLogMapper.selectExportLogList(exportLog));
    }

    /**
     * 列表展示数据处理
     *
     * @param exportLogs
     *            列表
     * @return 结果
     */
    private List<ExportLogDto> convert(List<ExportLogDto> exportLogs) {
        if (CollectionUtil.isEmpty(exportLogs)) {
            return exportLogs;
        }
        R<String> r = remoteConfigService.configInfoKey("export_expired_time");
        if (r.isNotSuccess()) {
            throw new BusinessException("参数获取失败");
        }
        Date expiredTime = DateUtils.findIndexDate(new Date(), -Integer.parseInt(r.getData())).getTime();

        exportLogs.forEach(exportLogDto -> {
            exportLogDto.setProcessedSize(exportLogDto.getBatchSize() * exportLogDto.getRemainBatch());
            if (Objects.nonNull(exportLogDto.getTotal())) {
                BigDecimal processedRatio = BigDecimal.valueOf(exportLogDto.getProcessedSize())
                    .divide(BigDecimal.valueOf(exportLogDto.getTotal()), 2, RoundingMode.HALF_UP);
                exportLogDto.setProcessedRatio(processedRatio);
            }
            // 验证是否过期
            if (exportLogDto.getGmtCreate().before(expiredTime)) {
                exportLogDto.setExportDetails(null);
            }
        });
        return exportLogs;
    }
}
